import { useState, useEffect, useRef } from "react"
import L from 'leaflet';
import lessModule from "./index.module.less"
import HomePage_MapComponent from "../../../../component/map";
import HomePage_PanoramicMonitoringPage_MapComponent_SubstationMarkerComponent from "./component/substationMarker";
import HomePage_PanoramicMonitoringPage_MapComponent_InfoWindowComponent from "./component/infoWindow";
import ReactDOM, { createRoot, Root } from "react-dom/client";
import HomePage_PanoramicMonitoringPage_MapComponent_SubstationMarkerInfoWindowComponent from "./component/substationMarkerInfoWindow";
import HomePage_PanoramicMonitoringPage_MapComponent_SubstationPolylineInfoWindowComponent from "./component/substationPolylineInfoWindow";
import axios from "axios";
import HomePage_PanoramicMonitoringPage_MapComponent_SubwayStationMarkerComponent from "./component/subwayStationMarker";
import { $beforeunload, $constantList, $eventBus, $EventBus_off, $EventBus_on, $nanoid_uuid, $StopPropagation, $websocketUrl } from "../../../../../../common/utils";
import ReconnectingWebSocket from "reconnecting-websocket";
import { useNavigate } from "react-router-dom";
import { message } from "antd";

// 主页-全景监控页面-地图组件 
const HomePage_PanoramicMonitoringPage_MapComponent: React.FC = () => {
    const navigate = useNavigate()
    const uuid = useRef<string>("")
    const socket = useRef<any>(null)
    const filterData = useRef<object>({})
    const sourceData = useRef<object>({})
    const mapStyleDaya = {
        position: "fixed",
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
    }
    let [funcData, setFuncData] = useState<object>({})
    const substationMarkerList = useRef<Array<object>>([])
    const subwayStationPointList = useRef<Array<L.LatLngExpression>>([])
    const subwayStationMarkerList = useRef<Array<L.Marker>>([])
    const substationPolylineList = useRef<Array<object>>([])
    const subwayStationPolylineList = useRef<Array<L.Polyline>>([])
    const subwayStationPolylinePointList = useRef<Array<Array<L.LatLngExpression>>>([])
    const isClickLine = useRef<boolean>(false)
    // 获取地铁数据
    const getJson_subway = () => {
        subwayStationPointList.current = []
        subwayStationPolylinePointList.current = []
        axios("./subway.json").then((res) => {
            res["data"].forEach((item: Array<object>) => {
                subwayStationPointList.current = [...subwayStationPointList.current, ...item["subwayStationList"]]
                item["polylineList"].forEach((item) => {
                    subwayStationPolylinePointList.current.push(item["spotList"])
                })
            })
            subwayStationPointList.current = Array.from(new Set(subwayStationPointList.current.map(item => JSON.stringify(item)))).map(item => JSON.parse(item))
            update_mapFuncData()
        })
    }

    // 变电站标记
    const marker_substation = (map: L.Map) => {
        const markerRoot_render = (markerRoot: Root, data: object, item = { mainIdx: 0 }) => {
            markerRoot.render(<HomePage_PanoramicMonitoringPage_MapComponent_SubstationMarkerComponent sourceData={data} mainIdx={item["mainIdx"] ?? 0} />);
        }
        const infowWindowRoot_render = (infowWindowRoot: Root, data: object, item = { mainIdx: 0 }) => {
            infowWindowRoot.render(<HomePage_PanoramicMonitoringPage_MapComponent_InfoWindowComponent title={data["stationName"]}
                change_navigate={() => navigate("/home/realRimeDynamics/singleMainTransformer", { state: { type: "主变", name: `${data["volLevel"]}${data["stationName"]}${data["monitorMain"][item["mainIdx"] ?? 0]["monitorMain"]}` } })}
                change_detail={() => $eventBus.emit("mapDetailModalOpen", { source: "HomePage_PanoramicMonitoringPage_MapComponent", explain: "请打开地图站点详情弹窗", data: { type: "站点",id:data["id"] } })}
                contentComponent={<HomePage_PanoramicMonitoringPage_MapComponent_SubstationMarkerInfoWindowComponent sourceList={data["monitorMain"]} change_mainIdx={(idx: number) => item["mainIdx"] = idx} />} />);
        }
        // 新增标记 
        sourceData.current["addStationInfo"]?.forEach((item: object) => {
            const markerElement = document.createElement('div');
            const markerRoot = createRoot(markerElement);
            markerRoot_render(markerRoot, item)
            const marker = L.marker([parseFloat(item["latitude"]), parseFloat(item["longitude"])] as L.LatLngExpression, {
                icon: L.divIcon({
                    html: markerElement,
                }),
                zIndexOffset: 1,
            }).addTo(map)

            const infowWindowElement = document.createElement('div');
            const infowWindowRoot = createRoot(infowWindowElement);
            item["monitorMain"].length && infowWindowRoot_render(infowWindowRoot, item)
            marker.bindPopup(infowWindowElement);
            substationMarkerList.current.push({ id: item["id"], markerRoot, marker, infowWindowElement, infowWindowRoot, mainIdx: 0 })

        })

        // 删除标记
        sourceData.current["delStationInfo"]?.forEach((item: object) => {
            const markerData = substationMarkerList.current.find((substationMarkerItem: object) => substationMarkerItem["id"] === item["id"]) ?? {}
            map.removeLayer(markerData["marker"])
            setTimeout(() => {
                markerData["markerRoot"].unmount();
                markerData["infowWindowRoot"].unmount();
            });

            substationMarkerList.current = substationMarkerList.current.filter((substationMarkerItem: object) => substationMarkerItem["id"] !== item["id"])
        })

        // 绑定dom
        substationMarkerList.current.forEach((item: object) => {
            const markerData = sourceData.current["stationInfo"].find((stationInfoItem: object) => stationInfoItem["id"] === item["id"])
            markerRoot_render(item["markerRoot"], markerData)
            markerData["monitorMain"].length && infowWindowRoot_render(item["infowWindowRoot"], markerData)
        })

    }

    // 地铁站标记
    const marker_subwayStation = (map: L.Map) => {
        if (map.getZoom() >= 12) {
            !subwayStationMarkerList.current.length && subwayStationPointList.current?.forEach((item, idx) => {
                const markerElement = document.createElement('div');
                const markerRoot = createRoot(markerElement);
                markerRoot.render(<HomePage_PanoramicMonitoringPage_MapComponent_SubwayStationMarkerComponent />);
                const marker = L.marker(item["latLngList"], {
                    icon: L.divIcon({
                        html: markerElement
                    })
                }).addTo(map)
                subwayStationMarkerList.current.push(marker)
            })
        } else {

            subwayStationMarkerList.current?.forEach((item, idx) => {
                map.removeLayer(item)
            })
            subwayStationMarkerList.current = []
        }
    }



    // 变电站线路
    const polyline_substation = (map: L.Map) => {
        const infowWindowRoot_render = (infowWindowRoot: Root, data: object) => {
            infowWindowRoot.render(<HomePage_PanoramicMonitoringPage_MapComponent_InfoWindowComponent title={data["line"]}
                change_navigate={() => navigate("/home/realRimeDynamics/singleLine", { state: { type: "线路", name: `${data["volLevel"]}${data["line"]}` } })}
                change_detail={() => $eventBus.emit("mapDetailModalOpen", { source: "HomePage_PanoramicMonitoringPage_MapComponent", explain: "请打开地图线路详情弹窗", data: { type: "线路",id:data["id"] } })}
                contentComponent={<HomePage_PanoramicMonitoringPage_MapComponent_SubstationPolylineInfoWindowComponent sourceData={data} />} />);
        }
        sourceData.current["addLineInfo"]?.forEach((item: object, idx: number) => {
            const polyline = L.polyline(item["connecSite"] as Array<L.LatLngExpression>, {
                weight: 2,
                color: item["status"] === 3 ? $constantList["stationStatusColor"][3] : "#1890FF",
            }).addTo(map);

            const infowWindowElement = document.createElement('div');
            const infowWindowRoot = createRoot(infowWindowElement);
            infowWindowRoot_render(infowWindowRoot, item)

            const infoWindowPopup = polyline.bindPopup(infowWindowElement);
            substationPolylineList.current.push({ id: item["id"], polyline, infowWindowElement, infowWindowRoot, infoWindowPopup, isInfoWindowPopupOpen: false });
            // 添加点击事件，确保在添加之前移除旧的事件  
            polyline.off("click").on("click", (e) => {
                isClickLine.current = true
                if (sourceData.current["lineInfo"].find((substationPolylineItem: object) => substationPolylineItem["id"] === item["id"])["status"] !== 3) {
                    if (substationPolylineList.current[idx]["isInfoWindowPopupOpen"]) {
                        e.target.setStyle({
                            weight: 2,
                        });
                        infoWindowPopup.closePopup();
                    } else {
                        e.target.setStyle({
                            weight: 6,
                        });
                        infoWindowPopup.openPopup();
                    }
                    substationPolylineList.current.forEach((polylineItem: object) => {
                        if (item["id"] === polylineItem["id"]) {
                            polylineItem["isInfoWindowPopupOpen"] = !polylineItem["isInfoWindowPopupOpen"]
                        } else {
                            polylineItem["isInfoWindowPopupOpen"] = false
                        }
                    })
                }
            });
        });

        // 删除线路  
        sourceData.current["delLineInfo"]?.forEach((item: object) => {
            const polylineData = substationPolylineList.current.find((substationMarkerItem: object) => substationMarkerItem["id"] === item["id"]) ?? {};
            map.removeLayer(polylineData["polyline"]);
            polylineData["infowWindowRoot"].unmount();
            polylineData["polyline"].unbindPopup(); // 确保移除弹窗绑定  
            substationPolylineList.current = substationPolylineList.current.filter((substationPolylineItem: object) => substationPolylineItem["id"] !== item["id"]);
        });

        // 更新信息窗口  
        substationPolylineList.current?.forEach((item: object) => {
            const polylineData = sourceData.current["lineInfo"].find((substationPolylineItem: object) => substationPolylineItem["id"] === item["id"]);
            item["polyline"].setStyle({
                color: polylineData["status"] === 3 ? $constantList["stationStatusColor"][3] : "#1890FF",
            });
            if (polylineData["status"] === 3) {
                // 关闭正在打开的线路弹窗
                item["infoWindowPopup"].closePopup()
                item["polyline"].setStyle({
                    weight: 2,
                });
                item["isInfoWindowPopupOpen"] = false
            } else {
                infowWindowRoot_render(item["infowWindowRoot"], polylineData)
            }
        });

    }
    // 地铁站线路
    const polyline_subwayStation = (map: L.Map) => {
        if (map.getZoom() >= 12) {
            !subwayStationPolylineList.current.length && subwayStationPolylinePointList.current?.forEach((item, idx) => {
                const polyline = L.polyline(item, {
                    weight: 2,
                    color: "#1890FF",
                    dashArray: '5, 5',
                }).addTo(map);
                subwayStationPolylineList.current.push(polyline)
            })
        } else {
            subwayStationPolylineList.current?.forEach((item, idx) => {
                map.removeLayer(item)
            })
            subwayStationPolylineList.current = []
        }
    }
    const click_map = () => {
        if (isClickLine.current) {
            isClickLine.current = false

        } else {
            substationPolylineList.current?.forEach((item: object) => {
                item["polyline"].setStyle({
                    weight: 2,
                })
                item["isInfoWindowPopupOpen"] = false
            })
        }
    }
    const socket_send = () => {
        socket.current.send(JSON.stringify(
            {
                token: sessionStorage.bearerToken,
                uuid: uuid.current,
                module: "overlay",
                type: "send",
                lastSourceData: sourceData.current,
                filterData: filterData.current,
            }
        ))
    }
    const ws_connect = () => {
        uuid.current = $nanoid_uuid()
        socket.current = new ReconnectingWebSocket($websocketUrl)


        socket.current.onopen = (data: object) => {
            // socket_send()
        }
        socket.current.onmessage = (data: object) => {
            data = JSON.parse(data["data"])
            if (data["status"] === 200) {

                sourceData.current = data
                setTimeout(() => {
                    $eventBus.emit("mapRealData", { source: "HomePage_PanoramicMonitoringPage_MapComponent", explain: "地图消息详情已发送！", data: { data: data } })
                });
                update_mapFuncData()
            } else {
                sourceData.current = {}
                message.error(data["error"])
                if (data["status"] === 401) {
                    navigate("/login"); //刷新 见 HomePage 
                }
            }
        }
        $beforeunload(socket.current, uuid.current, "overlay")
    }
    const ws_close = () => {
        socket.current.send(JSON.stringify(
            {
                uuid: uuid.current,
                module: "overlay",
                type: "close"
            }
        ))
        socket.current.close()
    }

    const update_mapFuncData = () => {
        funcData = {
            substationMarker: {
                isRefresh: true,
                func: marker_substation
            },
            subwayStationMarker: {
                isZoomRefresh: true,
                func: marker_subwayStation
            },
            substationPolyline: {
                isRefresh: true,
                func: polyline_substation
            },
            subwayStationPolyline: {
                isZoomRefresh: true,
                func: polyline_subwayStation
            },
        },

            setFuncData({ ...funcData })

    }
    // 广播函数数据
    const eventBusFuncData = {
        mapOverlayFilter: (data) => {
            if ("checkedData" in data["data"]) {
                filterData.current["checkedData"] = data["data"]["checkedData"]

            } else if ("timeAxisValue" in data["data"]) {
                filterData.current["timeAxisValue"] = data["data"]["timeAxisValue"]
            }
            if ("checkedData" in filterData.current && "timeAxisValue" in filterData.current) {
                socket_send()
            }
        }
    }

    useEffect(() => {
        getJson_subway()
        ws_connect()
        $EventBus_on(eventBusFuncData)
        return () => {
            $EventBus_off(eventBusFuncData)
            ws_close()
        }
    }, [])
    return (
        <div className={lessModule["homePagePanoramicMonitoringPageMapComponent"]} onClick={click_map}>
            {
                <HomePage_MapComponent styleData={mapStyleDaya} funcList={Object.values(funcData)} />
            }
        </div>
    )
}
export default HomePage_PanoramicMonitoringPage_MapComponent